#include "main.h"
#include "motor_protocol.h"
#include "usr_protocol.h"
 #include "utils.h"


#define UART1_RX_BUF_SIZE 128
#define UART2_RX_BUF_SIZE 128
#define UART1_TX_BUF_SIZE 128
#define UART2_TX_BUF_SIZE 128



static uint8_t uart1_rx_dma_buf[UART1_RX_BUF_SIZE];
static uint8_t uart2_rx_dma_buf[UART2_RX_BUF_SIZE];

 uint8_t uart1_tx_buf[UART1_TX_BUF_SIZE];
 uint8_t uart2_tx_buf[UART2_TX_BUF_SIZE];
 uint16_t uart1_rx_len = 0;
 uint16_t uart2_rx_len = 0;
 uint16_t uart1_tx_len = 0;
 uint16_t uart2_tx_len = 0;



typedef struct
{
	volatile uint8_t len;
  unsigned char buf[UART1_RX_BUF_SIZE];
} uart_recv_buf_t;


uint8_t group_1_id = 1;
uint8_t group_2_id = 1;
uint8_t group_1_id_testing = (int16_t)SLAVE_WAITING_RESPONSE;
uint8_t group_2_id_testing = (int16_t)SLAVE_WAITING_RESPONSE;

int16_t motor_status_reg_map[2][MAX_MOTOR_REG];
int16_t control_board_param_reg_map[2][MAX_BOARD_PARAM_REG];



// 位数组定义
uint32_t motor_position_flags[BIT_ARRAY_SIZE]; // 需要 (100+31)/32 = 4 个32位整数 = 16字节




int16_t *motor_actual_positon_base_addr[2] = {&motor_status_reg_map[0][1], &motor_status_reg_map[1][1]};
int16_t *motor_actual_erro_base_addr[2] = {&motor_status_reg_map[0][101], &motor_status_reg_map[1][101]};
int16_t *motor_actual_temp_base_addr[2] = {&motor_status_reg_map[0][201], &motor_status_reg_map[1][201]};
int16_t *motor_actual_current_base_addr[2] = {&motor_status_reg_map[0][301], &motor_status_reg_map[1][301]};
int16_t *motor_setpoint_positon_base_addr[2] = {&motor_status_reg_map[0][401], &motor_status_reg_map[1][401]};
int16_t *motor_control_reg_base_addr[2] = {&motor_status_reg_map[0][501], &motor_status_reg_map[1][501]};
int16_t *motor_status_reg_base_addr[2] = {&motor_status_reg_map[0][601], &motor_status_reg_map[1][601]};
int16_t *motor_uplimit_positon_base_addr[2] = {&motor_status_reg_map[0][701], &motor_status_reg_map[1][701]};
int16_t *motor_downlimit_position_base_addr[2] = {&motor_status_reg_map[0][801], &motor_status_reg_map[1][801]};
int16_t *motor_max_record_current_base_addr[2] = {&motor_status_reg_map[0][901], &motor_status_reg_map[1][901]};
int16_t *motor_max_record_temp_base_addr[2] = {&motor_status_reg_map[0][1001], &motor_status_reg_map[1][1001]};

int16_t *control_board_base_addr[2] = {&motor_status_reg_map[0][CONTROL_BOARD_STATUS],&motor_status_reg_map[1][CONTROL_BOARD_STATUS]};
int16_t *device_online_status_base_addr[2] ={ &control_board_param_reg_map[0][30], &control_board_param_reg_map[1][30]};

int16_t *sys_erro[2] = {&control_board_param_reg_map[0][SYS_ERRO_BASE],&control_board_param_reg_map[1][SYS_ERRO_BASE]};
int16_t *comm_error[2] = {&control_board_param_reg_map[0][COMM_ERROR_BASE],&control_board_param_reg_map[1][COMM_ERROR_BASE]};
int16_t *motor_err[2] = {&control_board_param_reg_map[0][MOTOR_ERROR_BASE],&control_board_param_reg_map[1][MOTOR_ERROR_BASE]};



static uart_recv_buf_t uart1_recv_buf;
static uart_recv_buf_t uart2_recv_buf;




void check_slave_timeout(uint8_t motor_group, uint8_t motor_id)
{
    if(motor_group ==0)
    {
        if(group_1_id_testing == (int16_t)SLAVE_WAITING_RESPONSE)
        {
            device_online_status_base_addr[motor_group][motor_id-1] = (int16_t)SLAVE_OFFLINE;
        }
    }
    else if(motor_group ==1)
    {
        if(group_2_id_testing == (int16_t)SLAVE_WAITING_RESPONSE)
        {
            device_online_status_base_addr[motor_group][motor_id-1] = (int16_t)SLAVE_OFFLINE;
        }
    }

}







void copy_data_to_uart_buffer(const uint8_t *data, uart_recv_buf_t *uart1_recv_buf, uint8_t length)	;
/* USER CODE BEGIN Header_StartTask02 */
/**
* @brief Function implementing the uart_thread thread.
* @param argument: Not used
* @retval None
*/
/* USER CODE END Header_StartTask02 */
void UartTask(void const * argument)
{

    uint16_t group_1_max_id = control_board_param_reg_map[0][MAX_ID_ADDR];
    uint16_t group_2_max_id = control_board_param_reg_map[1][MAX_ID_ADDR];

    if(group_1_max_id > MAX_ID)
        group_1_max_id = MAX_ID;
    if(group_2_max_id > MAX_ID)
        group_2_max_id = MAX_ID;
    if(group_1_max_id  ==0 )
        group_1_max_id = MAX_ID;
    if(group_2_max_id  ==0 )
        group_2_max_id = MAX_ID;
    

  /* USER CODE BEGIN StartTask02 */
    // 使能UART1空闲中断
   __HAL_UART_ENABLE_IT(&huart1, UART_IT_IDLE);
   HAL_UART_Receive_DMA(&huart1, uart1_rx_dma_buf, UART1_RX_BUF_SIZE);

    // 使能UART2空闲中断
   __HAL_UART_ENABLE_IT(&huart2, UART_IT_IDLE);
  HAL_UART_Receive_DMA(&huart2, uart2_rx_dma_buf, UART2_RX_BUF_SIZE);



    

  /* Infinite loop */
  for(;;)
  {
    if(osSemaphoreWait(uart1_semHandle, 0) == osOK)
    {
        if(process_protocol_data(0,uart1_recv_buf.buf,uart1_recv_buf.len) == 1)
        {
            group_1_id_testing =(int16_t)SLAVE_ONLINE;
        }
    }
    if(osSemaphoreWait(uart2_semHandle, 0) == osOK)
    {
        if(process_protocol_data(1,uart2_recv_buf.buf,uart2_recv_buf.len) ==1)
        {
            group_2_id_testing =(int16_t)SLAVE_ONLINE;
        }
        
    }
    check_slave_timeout(0, group_1_id);
    check_slave_timeout(1, group_2_id);

    osEvent event = osMessageGet(uartFrameQueueHandle, 0);  // 非阻塞

    if (event.status == osEventMessage) {
        // 对于直接复制数据的队列，event.value.p 给出指向队列内部存储的指针
        UartFrameCommand_t* cmd = (UartFrameCommand_t*)event.value.p;
        if(cmd != NULL)
        {
            if (cmd->motor_group == 0) {
                // UART1处理
                memcpy(uart1_tx_buf, cmd->frame_data, cmd->frame_length);
   
                uart1_tx_len = cmd->frame_length;
                HAL_GPIO_WritePin(rs485_cs1_port, rs485_cs1_pin, GPIO_PIN_SET);
                        // 使能UART1发送完成中断

                __HAL_UART_CLEAR_FLAG(&huart1, UART_FLAG_TC);  // Clear TC flag first
                __HAL_UART_ENABLE_IT(&huart1, UART_IT_TC);
                HAL_UART_Transmit_DMA(&huart1, uart1_tx_buf, uart1_tx_len);
            } else if (cmd->motor_group == 1) {
                // UART2处理
                memcpy(uart2_tx_buf, cmd->frame_data, cmd->frame_length);

                uart2_tx_len = cmd->frame_length;
                HAL_GPIO_WritePin(rs485_cs2_port, rs485_cs2_pin, GPIO_PIN_SET);
                // 使能UART2发送完成中断
                __HAL_UART_CLEAR_FLAG(&huart2, UART_FLAG_TC);  // Clear TC flag first
                __HAL_UART_ENABLE_IT(&huart2, UART_IT_TC);
                HAL_UART_Transmit_DMA(&huart2, uart2_tx_buf, uart2_tx_len);
            }
            
            osPoolFree(uartCmdPoolHandle, cmd);
        }


    }
    else
    {
        group_1_id++;
        if(group_1_id >= group_1_max_id)
        {
            group_1_id = 1;
        }

        group_2_id++;
        if(group_2_id >= group_2_max_id)
        {
            group_2_id = 1;
        }
        
        group_1_id_testing = (int16_t)SLAVE_WAITING_RESPONSE;
        group_2_id_testing = (int16_t)SLAVE_WAITING_RESPONSE;

        uart1_tx_len = build_command_frame(uart1_tx_buf, group_1_id, CMD_READ_STATUS, 0x0000, NULL, 0);

        HAL_GPIO_WritePin(rs485_cs1_port, rs485_cs1_pin, GPIO_PIN_SET);
        __HAL_UART_CLEAR_FLAG(&huart1, UART_FLAG_TC);  // Clear TC flag first
        __HAL_UART_ENABLE_IT(&huart1, UART_IT_TC);
        HAL_UART_Transmit_DMA(&huart1, uart1_tx_buf, uart1_tx_len);
        group_1_id_testing = (int16_t)SLAVE_WAITING_RESPONSE;


        uart2_tx_len = build_command_frame(uart2_tx_buf, group_2_id, CMD_READ_STATUS, 0x0000, NULL, 0);
        HAL_GPIO_WritePin(rs485_cs2_port, rs485_cs2_pin, GPIO_PIN_SET);
        __HAL_UART_CLEAR_FLAG(&huart2, UART_FLAG_TC);  // Clear TC flag first
        __HAL_UART_ENABLE_IT(&huart2, UART_IT_TC);
        HAL_UART_Transmit_DMA(&huart2, uart2_tx_buf, uart2_tx_len);

    }

    osDelay(10);
  }
  /* USER CODE END StartTask02 */
}




void UART_IDLECallback(UART_HandleTypeDef *huart)
{
    if(huart == &huart1)
    {
        osSemaphoreRelease(uart1_semHandle);
        // 清除空闲中断标志
        __HAL_UART_CLEAR_IDLEFLAG(&huart1);
        
        // 获取DMA中接收到的数据长度
        uart1_rx_len = UART1_RX_BUF_SIZE - __HAL_DMA_GET_COUNTER(huart1.hdmarx);
        
        // 处理数据
        memcpy(uart1_recv_buf.buf, uart1_rx_dma_buf, uart1_rx_len);
        uart1_recv_buf.len = uart1_rx_len;
        // ...
        
        // 重启DMA接收
        HAL_UART_DMAStop(&huart1);
        HAL_UART_Receive_DMA(&huart1, uart1_rx_dma_buf, UART1_RX_BUF_SIZE);
    }
    else if(huart == &huart2)
    {
        osSemaphoreRelease(uart2_semHandle);
        __HAL_UART_CLEAR_IDLEFLAG(&huart2);
        uart2_rx_len = UART2_RX_BUF_SIZE - __HAL_DMA_GET_COUNTER(huart2.hdmarx);
        
        // 处理数据
        memcpy(uart2_recv_buf.buf, uart2_rx_dma_buf, uart2_rx_len);
        uart2_recv_buf.len = uart2_rx_len;
        // ...
        
        HAL_UART_DMAStop(&huart2);
        HAL_UART_Receive_DMA(&huart2, uart2_rx_dma_buf, UART2_RX_BUF_SIZE);
    }
}



// First, add the callback function
void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
{
    if (huart == &huart1)
    {
        // 清除发送完成标志
        __HAL_UART_CLEAR_FLAG(huart, UART_FLAG_TC);
        // Set RS485 back to receive mode
        HAL_GPIO_WritePin(rs485_cs1_port, rs485_cs1_pin, GPIO_PIN_RESET);
    }
    else if (huart == &huart2)
    {
        // Set RS485 back to receive mode
        // 清除发送完成标志
        __HAL_UART_CLEAR_FLAG(huart, UART_FLAG_TC);
        HAL_GPIO_WritePin(rs485_cs2_port, rs485_cs2_pin, GPIO_PIN_RESET);
    }
}